package com.hns.can.energy.component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.component.BaseQuartzJob;
import com.hns.can.base.entity.AppOilPriceEntity;
import com.hns.can.base.service.SysTimeService;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.service.CacheTaskManager;
import com.hns.can.common.vo.SysCacheVo;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilString;

@Component
public class EnergyPriceQuartzJob extends CommonService implements BaseQuartzJob{

	protected static final Logger log = LoggerFactory.getLogger(SysTimeService.class);
	
	@Autowired
    private CacheTaskManager cacheTaskManager;
	
	@Transactional(rollbackFor=Exception.class)
	public void runQuartzJob() throws JSONException,Exception{
		log.error("===================开始执行定时任务====================");
		HashMap map = (HashMap)cacheTaskManager.loadCache(GlobalConst.CACHE_KEY_SYS_CODE, "39708c61759b48748c5bd853ba64ded5");
		List list= (List) map.get("ADS00000");
		List<String> citys=new ArrayList<String>();
		List<AppOilPriceEntity> listEnergy= PubUtil.convertListMapToObject(sqlMapDao.selectList("oilPrice.searchAllEnergyInfo"), AppOilPriceEntity.class);
		//所有省份
		for(int i=0;i<list.size();i++){
			SysCacheVo Voentity=(SysCacheVo) list.get(i);
			String pro=Voentity.getValue();
			String province=pro.replaceAll("省", "");
			if(!("香港".equals(province)||"澳门".equals(province)||"台湾".equals(province))){
				List cityKey= (List) map.get(Voentity.getKey());
				JSONObject oilinfo = null;
				try {
					oilinfo = getEnergyFromApi(province);
				} catch (Exception e) {
					break;
				}
				for(int j=0;j<cityKey.size();j++){
					SysCacheVo city=(SysCacheVo) cityKey.get(j);
					String cityId=city.getKey();
					try {
						getEnergyByApi(province,Voentity.getKey(),city.getKey(),listEnergy,oilinfo);
					} catch (Exception e) {
						break;
					}
				}
			}
		}
		log.error("===================执行定时任务结束====================");
	}
	
	//对比每个城市的油价,油价不同就保存
    public void getEnergyByApi(String province,String provinceId,String cityId,List<AppOilPriceEntity> listEnergy,JSONObject data1) throws Exception {
        String time=getOilAdjustDate(data1);
        BigDecimal[] oilPrice=getOilPrice(data1);
        String[] oilType={"FUT00001","FUT00002","FUT00003","FUT00004"};
        boolean judge=true;
        for(int n=0;n<listEnergy.size();n++){
			if(cityId.equals(listEnergy.get(n).getCityId())){
				judge=false;
				for(int j=0;j<oilType.length;j++){
					AppOilPriceEntity tmp = listEnergy.get(n);
	        		BigDecimal oilPriceSql = tmp.getPrice();
	        		String oilTypeSql = tmp.getOilType();
	        		if(oilTypeSql.equals(oilType[j]) && !oilPriceSql.equals(oilPrice[j])){
	        			saveEnergyinfo(cityId,provinceId,oilType[j],oilPrice[j], time);
	        		}
				}
			}
		}
        if(judge){
        	for(int j=0;j<oilType.length;j++){
        		saveEnergyinfo(cityId,provinceId,oilType[j],oilPrice[j], time);
        	}
		}
	 }
    
    //将油价从JSON中提取出来
    public BigDecimal[] getOilPrice(JSONObject data1){
    	BigDecimal FUT00001=new BigDecimal(data1.get("p90").toString());
        BigDecimal FUT00002=new BigDecimal(data1.get("p93").toString());
        BigDecimal FUT00003=new BigDecimal(data1.get("p97").toString());
        BigDecimal FUT00004=new BigDecimal(data1.get("p0").toString());
        BigDecimal[] oilPrice={FUT00001,FUT00002,FUT00003,FUT00004};
        return oilPrice;
    }
    
    //将油价调整时间从JSON中提取出来转换成数据库需要的格式
    public String getOilAdjustDate(JSONObject data1) throws Exception{
    	String time=data1.get("ct").toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date=sdf.parse(time);
        time=sdf.format(date);
        return time;
    }
    
    //通过API获取省份的油价
    public JSONObject getEnergyFromApi(String province) throws Exception{
    	List<AppOilPriceEntity> list = new ArrayList<AppOilPriceEntity>();
		String httpUrl = "http://apis.baidu.com/showapi_open_bus/oil_price/find";
		//province = URLEncoder.encode(province, "UTF-8");
		String httpArg = "prov="+URLEncoder.encode(province, "UTF-8");
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;
	    
	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey",  "3a1a1ef1f8a718194dbeb3c2cccbfa8b");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	        //转换成JSON对象
	        JSONObject resJson=new JSONObject(result);
	        JSONObject data=resJson.getJSONObject("showapi_res_body");
	        //找到list中我们所需要的内容
	        String a=data.get("list").toString();
	        //由于字符串中有[] 不能转换为JSON对象，需要用正则表达式去掉
	        String b = a.replaceAll("\\[([^\\]]*)\\]", "$1");
	        if("北京".equals(province) || "上海".equals(province)){
	        	b = b.replaceAll("\\([^)]+\\)","");
	        }
	        JSONObject data1 = new JSONObject(b);
	        return data1;
	    	} catch (Exception e) {
	    		 e.printStackTrace();
	    	}
		return null;
    }
    //将信息存到数据库
    public void saveEnergyinfo(String cityId,String provinceId,String oilType,BigDecimal oilPrice,String time){
    	log.error("===================更新"+cityId+"油价信息====================");
    	AppOilPriceEntity entity = new AppOilPriceEntity();
		entity.setId(UtilString.getUUID());
		entity.setCityId(cityId);
		entity.setProvinceId(provinceId);
		entity.setOilType(oilType);
		entity.setPrice(oilPrice);
		entity.setAdjustDate(time);
		entity.setCrtTime(new Date());
		entity.setCrtUser("system");
		commonEntityDao.save(entity);
    }
	
}
